import {connect} from 'react-redux'
import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {View, Block, Button} from '@tarojs/components'
import {AtButton} from 'taro-ui'
import {GetRequest, clearSearch} from "../../utils/tools";
import {user} from '../../utils/user.service'
import {getRedBagSet} from '../../actions/redbag'
import {platform} from "../../utils/platform-settting.service";
import {http} from "../../utils/http";
import {GET_PHONE, MERGE_USER} from "../../constants/api";
import './login.scss'

interface ServerPhone {
  phoneNumber: string
  purePhoneNumber: string
  countryCode: string
  isForceMergeAccount?: boolean
  watermark: {
    timestamp: number
    appid: string
  }
}

interface LoginParamType {
  nickName: string
  gender: number
  language: string
  city: string
  province: string
  country: string
  avatarUrl: string
  bindSellerId: number
  itemUUID: string
  path: string
}

type PageStateProps = {}

type PageDispatchProps = {
  getSet: any
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Login {
  props: IProps
}

@connect(({}) => ({}), (dispatch) => ({
  getSet() {
    dispatch(getRedBagSet())
  }
}))

class Login extends Component {
  state: {
    loginParam: LoginParamType
    isOpen: boolean
  } = {
    loginParam: {
      nickName: '',
      gender: 1,
      language: '',
      city: '',
      province: '',
      country: '',
      avatarUrl: '',
      bindSellerId: 0,
      itemUUID: '',
      path: '',
    },
    isOpen: false
  }

  type = platform.info.authorizationType
  loginmsg: any

  async componentDidShow() {
    clearSearch()
    if (this.type && process.env.TARO_ENV === 'weapp') {
      const loginParam = this.state.loginParam
      Taro.login().then(async code => {
        user.code = code.code
        const ret = await user.doLogin(loginParam)
        if (!ret) {
          Taro.showToast({
            title: '授权失败,请退出小程序重试',
            icon: 'none'
          })
          return
        }
        this.loginmsg = ret
      })
    }
  }

  goBack(num?: number) {
    const {delta} = Taro.getCurrentInstance().router.params; // 手动退回页面数
    let backNum = parseInt(delta || 1);
    if (num && typeof num === "number") {
      backNum = num; // 流程中控制(授权成功后)
    }
    if (this.state.isOpen) return
    Taro.navigateBack({
      delta: backNum
    })
  }

  getToken(num) {
    const res = Taro.getStorageSync("user")
    if (num < 100) {
      if (res.token) {
        return true
      } else {
        return this.getToken(num++)
      }
    } else {
      return false
    }
  }

  async ttGetUserInfo() {
    await this.commonGetUserInfo()
  }

  async commonGetUserInfo() {
    this.setState({isOpen: true})
    await Taro.showLoading({title: '授权中...', mask: true})
    const ret = await user.serverLogin()
    Taro.hideLoading()
    if (ret) {
      await Taro.showToast({
        title: '授权成功',
        mask: true
      })
      this.setState({isOpen: false})
      const timer = setTimeout(() => {
        clearTimeout(timer)
        this.goBack(1)
      }, 1000)
    } else {
      this.setState({isOpen: false})
      await Taro.showToast({
        mask: true,
        icon: 'none',
        title: '授权失败'
      })
      return false
    }
  }

  async getUserInfo(res) {
    if (this.state.isOpen) return
    if (res.detail.errMsg.indexOf('ok') > -1) {
      await this.commonGetUserInfo()
    } else {
      Taro.showModal({
        title: '提示',
        content: '需要获取登录权限，请打开"使用我的用户信息", 然后再点击登录',
        success: (ret) => {
          if (ret.confirm) {
            Taro.openSetting()
          } else {
            this.goBack()
          }
        }
      })
    }
  }

  async getPhoneNumber(data) {
    const ret = this.loginmsg
    try {
      if (ret && ret.token) {
        if (data && data.detail && data.detail.errMsg.indexOf('ok') > -1) {
          const res = await http.post<ServerPhone>(GET_PHONE, {
            encryptedData: data.detail.encryptedData,
            iv: data.detail.iv
          })
          if (res) {
            Taro.setStorageSync('wxPhone', res.phoneNumber)
            user.token = ret.token
            const userData = ret
            user.userInfo = userData
            user.isLogin = true
            Taro.setStorageSync('user', {token: ret.token, userInfo: userData})
            await Taro.showToast({title: '登录成功！', mask: true})
            if (res.isForceMergeAccount) {
              http.postCar(MERGE_USER, {phone: res.phoneNumber})
            }
            const timer = setTimeout(() => {
              clearTimeout(timer)
              this.goBack()
            }, 1200)
          } else {
            await Taro.showModal({
              title: '提示',
              content: '需要获取手机号，请打开"使用我的用户信息", 然后再点击登录',
              success: (result) => {
                if (result.confirm) {
                  Taro.openSetting()
                } else {
                  this.goBack()
                }
              }
            })
          }
        }
      } else {
        user.logout()
      }
    } catch (error) {
    }
  }

  confirmAuthorization() {
    Taro.showLoading({title: '登录中...'})
    window.location.replace(window.location.search.substr(9, window.location.search.length))
  }

  render() {
    const {isOpen} = this.state
    return (
      <View className='login-wrapper' style=''>
        <View className='user-authorization-title'>用户授权</View>
        {process.env.TARO_ENV === 'h5' && <View>
          <View
            className='confirm-authorization-title'
          >为提供更好的服务，需要授权允许使用您的微信公开信息（昵称，头像等），请点击下面的授权按钮。</View>
          <AtButton type='primary' onClick={this.confirmAuthorization.bind(this)}>确认授权</AtButton>
        </View>}
        {process.env.TARO_ENV === 'tt' && <Block>
          <View
            className='confirm-authorization-title'
          >为提供更好的服务，需要授权允许使用您的微信公开信息（昵称，头像等），请点击下面的授权按钮。</View>
          <View style='margin-top: 150rpx;'><Button className='at-button--primary' openType='getUserInfo'
            onClick={this.ttGetUserInfo.bind(this)}
          >确认授权</Button></View>
          <View style='margin-top: 30rpx;'><AtButton type='secondary'
            onClick={this.goBack.bind(this)}
          >返回</AtButton></View>
        </Block>}
        {process.env.TARO_ENV === 'weapp' && <View>
          {this.type ?
            <Block>
              <View
                className='confirm-authorization-title'
              >为提供更好的服务，需要授权允许使用您的微信公开信息（手机号等），请点击下面的授权按钮。</View>
              {(process.env.TARO_ENV === 'weapp' || process.env.TARO_ENV === 'tt') &&
                <View style='margin-top: 150rpx;'>
                  <Button className='at-button--primary' open-type='getPhoneNumber'
                    ongetphonenumber={this.getPhoneNumber.bind(this)}
                  >确认授权</Button>
                </View>}
              <View style='margin-top: 30rpx;'><AtButton type='secondary' disabled={isOpen}
                onClick={this.goBack.bind(this)}
              >返回</AtButton></View>
            </Block>
            :
            <Block>
              <View
                className='confirm-authorization-title'
              >为提供更好的服务，需要授权允许使用您的微信公开信息（昵称，头像等），请点击下面的授权按钮。</View>
              {(process.env.TARO_ENV === 'weapp' || process.env.TARO_ENV === 'tt') &&
                <View style='margin-top: 150rpx;'><Button className='at-button--primary' openType='getUserInfo'
                  onGetUserInfo={this.getUserInfo.bind(this)}
                >确认授权</Button></View>}
              <View style='margin-top: 30rpx;'><AtButton type='secondary'
                onClick={this.goBack.bind(this)}
              >返回</AtButton></View>
            </Block>
          }
        </View>}
      </View>
    )
  }
}

export default Login as ComponentClass<PageOwnProps, PageState>
